<template>
  <div class="login">
    <h1>登录</h1>
    <van-form @submit="login">
      <van-field
        v-model="formData.phone"
        placeholder="用户名"
        :rules="[{ required: true, message: '请填写用户名' }]"
      />
      <van-field
        v-model="formData.pass"
        type="password"
        placeholder="输入密码"
        :rules="[{ required: true, message: '请填写密码' }]"
      />
      <div style="margin: 16px">
        <van-button round block type="info" native-type="submit">登录</van-button>
      </div>
    </van-form>
  </div>
</template>

<script>
import { Toast } from 'vant';
import {user_login} from '../utils/api'
export default {
     data() {
    return {
      formData:{
        phone:'',
        pass:''
      }
    }
  },
  methods: {
    login(){
      //发起登陆请求
      user_login( this.formData ).then((res)=>{
        if( res.data.code == 200 ){
          //保存用户信息,token
          localStorage.setItem('token',res.data.token);
          localStorage.setItem('userinfo', JSON.stringify( res.data.userinfo ) );
          //自动跳转到首页
          this.$router.push('/');
          Toast.success('登陆成功!')
        }else{
          Toast.fail('登陆失败!')
        }
      })
    }
  },
};
</script>

<style lang='scss' scoped>
    h1{
        text-align: center;
        margin-bottom: 50px;
    }
</style>